﻿using System;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using Nito.MVVM;
using NUnit.Framework;
using Present.Commands.Decorators;
using Rhino.Mocks;

namespace Present.Commands.Tests.Decorators
{

    public class MockCommandDecorator : CommandDecorator<ICommand>
    {
        public MockCommandDecorator(ICommand innerCommand) : base(innerCommand)
        {
        }
    }

    [TestFixture]
    public class CommandDecoratorTestCase
    {
        private ICommand command;

        [SetUp]
        public void SetUp()
        {
            command = new MockCommandDecorator(MockRepository.GenerateStub<ICommand>());
        }

        [Test]
        public void ShouldNotRootSubscribers()
        {

            WeakReference reference = null;
            Action perform = () =>
                                 {
                                     reference = new WeakReference(new Listener(command));
                                 };

            perform();

            GC.Collect();
            GC.WaitForPendingFinalizers();


            Assert.IsNull(reference.Target);
        }



        class Listener
        {
            private readonly EventHandler handler;
            public Listener(ICommand command)
            {
                // attach an event listner; this adds a reference to the
                // source_SomeEvent method in this instance to the invocation list
                // of SomeEvent in source
                handler = new EventHandler(Handle);
                command.CanExecuteChanged += handler;
            }

            void Handle(object sender, EventArgs e)
            {
                // whatever
            }
        }

    }
}